<?php
/**
 * Description: 处理微信的请求
 * User: wh
 * Date: 2017-07-26
 * Time: 11:03
 */
namespace app\wxbackend\controller\Wx;
use app\wxbackend\controller\MemberController;
use app\wxbackend\model\Member;
use think\Controller;

class WxRequest extends Controller{
    /**
     * @comment 统一处理入口
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function handle(&$request)
    {
        switch ($request['msgtype']) {
            //事件
            case 'event':
                $request['event'] = strtolower($request['event']);
                switch ($request['event']) {
                    //关注
                    case 'subscribe':
                        $data = self::eventSubscribe($request);
                        break;
                    case 'unsubscribe':
                        $data = self::eventUnSubscribe($request);
                        break;
                    //扫描二维码
                    case 'scan':
                        $data = self::eventScan($request);
                        break;
                    //地理位置
                    case 'location':
                        $data = self::eventLocation($request);
                        break;
                    //自定义菜单 - 点击菜单拉取消息时的事件推送
                    case 'click':
                        $data = self::eventClick($request);
                        break;
                    //自定义菜单 - 点击菜单跳转链接时的事件推送
                    case 'view':
                        $data = self::eventView($request);
                        break;
                }
                break;
            case 'text':
                $data = self::text($request);
                break;
            case 'image':
                $data = self::image($request);
                break;
            case 'voice':
                $data = self::voice($request);
                break;
            case 'video':
                $data = self::video($request);
                break;
            case 'shortvideo':
                $data = self::shortvideo($request);
                break;
            case 'location':
                $data = self::location($request);
                break;
            case 'link':
                $data = self::link($request);
                break;
            default:
                break;

        }

        return $data;
    }

    /**
     * @comment 文本
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function text(&$request)
    {
        $content = '';
        switch ($request['content']) {
            case '1':
                $content = $request['fromusername'];
                return WxResponse::text($request['fromusername'], $request['tousername'], $content);
                break;
            case '2': //测试oauth2用的 ok
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=http://zft.louxiaomei.com/index/wx/oauth2&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
                $content = "OAuth2.0网页授权演示
            <a href=\"$url\">点击这里体验</a>";
                return WxResponse::text($request['fromusername'], $request['tousername'], $content);
                break;
            case '3' : //测试oauth2获取access_token用的 ok
                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=011nLWNF0G1lei2WvXOF0G2PNF0nLWNa&grant_type=authorization_code";
                $content = "获取AccessToken
                <a href=\"$url\">点击</a>";
                return WxResponse::text($request['fromusername'], $request['tousername'], $content);
                break;
            case '4'://测试session
                //$_SESSION = [];
                //session_destroy();
                WxSession::setSession($request['fromusername']);
                zft_log('wx/test', json_encode($_SESSION));
                $content = isset($_SESSION) ? 'openid:'.session('openid').' mid'.session('mid') : '没有session';
                return WxResponse::text($request['fromusername'], $request['tousername'], $content);
                break;
            default:
                $content = '未知请求';
                return WxResponse::text($request['fromusername'], $request['tousername'], $content);
                break;
        }
    }

    /**
     * @comment 图片
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function image(&$request)
    {
        $content = '收到图片';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 语音
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function voice(&$request)
    {
        if(!isset($request['recognition'])) {
            $content = '收到语音';
        } else {
            $content = '收到语音识别消息，语音识别结果为：'.$request['recognition'];
        }
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 视频
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function video(&$request)
    {
        $content = '收到视频';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 小视频
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function shortvideo(&$request)
    {
        $content = '收到小视频';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 地理位置
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function location(&$request)
    {
        $content = '收到地理位置';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 链接
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function link(&$request)
    {
        $content = '收到链接';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    public static function msgDefault(&$request)
    {
        $content = '未能识别您的请求信息';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }
    /**
     * @comment 关注事件
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function eventSubscribe(&$request)
    {
        $memberModel = new Member();
        if ($memberModel->getMemberByOpenid($request['fromusername'])) {
            $content = '您已关注租付通，无需重复关注';
        } else {
            //关注
            $data = [
                'openid' => $request['fromusername'],
                'create_time' => date('Y-m-d H:i:s'),
                'status' => 0,
                'dtype' => '',
                'pdtype' => ''
            ];
            if (!$memberModel->addWxInfo($data)) {
                zft_log('wx/sub', $memberModel->getLastSql());
            }

            WxSession::setSession($request['fromusername']);
            $content = "您好，感谢关注租付通！租付通（www.louxiaomei.com）是国内领先的SaaS模式楼宇智能化资产管理云平台，通过互联网技术+智能硬件构建的全方位楼宇智能化管理生态系统，全方位提升楼宇产权方、运营管理者的招商和运营能力，实现智能化、信息化、数据化、安全化的楼宇管理，高效解决目前楼宇管理工作中存在的招商慢、管理乱、收租难等问题。同时帮助楼宇产权方实现资产证券化，解决“有资产没钱花”的问题。";
        }

        //zft_log('wx/subscribe',$request['fromusername'] );
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 取消关注
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function eventUnSubscribe(&$request)
    {
        $memberModel = new Member();
        if (!$memberModel->deleteInfo($request['fromusername'])) {
            zft_log('zft/unsub', $memberModel->getLastSql());
        }
        unset($_SESSION);
        session_destroy();
        $content = '已取消关注';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 已关注扫码
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function eventScan(&$request)
    {
        $content = '您已关注租付通';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 地理位置
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function eventLocation(&$request)
    {
        $content = '收到地理位置';
        return WxResponse::text($request['fromusername'], $request['tousername'], $content);
    }

    /**
     * @comment 自定义菜单click类型
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function eventClick(&$request)
    {
        $eventKey = strtolower($request['eventkey']);
        switch ($eventKey) {
            case 'index_1': //什么都不做
            case 'index_2':
                return '';
                break;
            case 'statistics':
                $url = 'http://staticzft.louxiaomei.com/analyse?openid='.$request['fromusername'];

                WxSession::setSession($request['fromusername']);
                zft_log('test', json_encode($_SESSION));

                //$stript  = "<script>location.href='{$url}';</script>";
                //Header("Location: $url", true, 301);
                //exit;
                return WxResponse::text($request['fromusername'], $request['tousername'], session('openid'));
                break;
            case 'unbind'://取消绑定
                $memberModel = new Member();
                $wxInfo      = $memberModel->getMemberByOpenid($request['fromusername']);
                $account     = $wxInfo['account'];
                if (!$memberModel->updateInfo(['openid' => $request['fromusername']],
                    ['status' => 0, 'mobile' => '', 'account' => '', 'mid' => '', 'pmid' => '', 'dtype' => '', 'pdtype' => ''])
                ) {
                    zft_log('zft/unbind', $memberModel->getLastSql());
                    $content = '取消失败';
                } else {
                    $content = '取消绑定成功';
                    //更新菜单,取消用户标签
                    $mInfo = $memberModel->getMemberByAccount($account);
                    //zft_log('wx/cancel_tags', $account);
                    switch ($mInfo['dtype']) {
                        case 0:
                            $tagId = 104;
                            break;
                        case 2:
                            $tagId = 102;
                            break;
                        default:
                            $tagId = 103;
                            break;
                    }
                    //$tagId = $mInfo['dtype'] == 2 ? 102 : 103;
                    //zft_log('wx/cancel_tags', json_encode($mInfo));
                    WxTags::cancelTags([$request['fromusername']], $tagId);

                    //设置session
                    WxSession::setSession($request['fromusername']);
                    session('mid', '');
                    session('pmid', '');
                    session('account', '');
                    session('mobile', '');
                    session('status', '');
                    session('dtype', '');
                    session('pdtype', '');
                }
                return WxResponse::text($request['fromusername'], $request['tousername'], $content);
                break;
            default:
                $content = '未知请求';
                return WxResponse::text($request['fromusername'], $request['tousername'], $content);
                break;
        }
    }

    /**
     * @comment 自定义菜单view类型
     * @author wuhao
     * @param $request
     * @return string
     */
    public static function eventView(&$request)
    {
        return '';
    }
}